class TreeNode:
    def __init__(self, value):
        self.value, self.left, self.right = value, None, None

def build_expression_tree(postfix_expr):
    stack, operators = [], {'+', '-', '*', '/'}
    for token in postfix_expr:
        if token in operators:
            # Create operator node; pop right then left; attach; push back
        else:
            # Push a new TreeNode for the operand
    return stack[0]

def preorder_traversal(node):
    if not node: return []
    # Return root value + preorder(left) + preorder(right)

# --- Main Program ---
def solve():
    input() # Read and ignore N
    postfix_expr = input().strip().split()

    # 1. Build the tree
    root = build_expression_tree(postfix_expr)
    
    # 2. Traverse the tree
    prefix_expr = preorder_traversal(root)

    # 3. Print the result
    print(" ".join(prefix_expr))

solve()

Assembling the Solver 🧩

This slide shows the complete Python code to solve the problem. The key steps are:

  1. Build Tree: Construct an expression tree from the postfix input.
  2. Traverse Tree: Perform a preorder traversal on the tree to get the prefix expression.
  3. Print Result: Output the final prefix expression.
Lab Complete!